
//保存按钮
jQuery(".saveBtn").on('click',function(){
	saveTicket(1);	
});
////保存申请
function saveTicket(re,fileType,numId){
	if (jQuery("#ticketForm") && !jQuery("#ticketForm").Validform({
		tiptype : 3,
		showAllError : true
	}).check(false)) {
		return;
	}
	var contractId = jQuery("#contractId").val();
	var deviceId = jQuery("#deviceId").val();
	var url = window.rootPath+'/ui/afterSaleTicket/save';
	var id = jQuery("#id").val();
	var ticketCreateTime=jQuery("#ticketCreateTime").val();
	var createTime= new Date(ticketCreateTime).getTime();
	var superior = jQuery("#superior").val();
	var unitName = jQuery("#unitName").val();
	var contractCode = jQuery("#contractCode").val();
	var proposer = jQuery("#proposer").val();
	var linkMan = jQuery("#linkMan").val();
	var linManPhone = jQuery("#linkManPhone").val();
	var afterSaleType = jQuery("#afterSaleType").val();
	var deviceCode = jQuery("#deviceCode").val();
	var deviceName = jQuery("#deviceName").val();
	var deviceNumber = jQuery("#deviceNumber").val();
	var questionDetail = jQuery("#questionDetail").val();
	var serviceTime=jQuery("#serviceTime").val();
	var submiterId=jQuery("#submiter").val();
    	if(id == ''){
    		var d = {
    				"superior":superior,
    				"isSubmit":0,
    				"unitName" : unitName,
    				"contractCode" : contractCode,
    				"contractId" : contractId,
    				"proposer" : proposer,
    				"linkMan" : linkMan,
    				"linkManPhone" : linManPhone,
    				"afterSaleType" : afterSaleType,
    				"deviceName" : deviceName,
    				"deviceCode" : deviceCode,
    				"deviceNumber" : deviceNumber,
    				"questionDetail" : questionDetail,
    				"serviceTime" : serviceTime,
    				"submiter" : {
    					     "id":submiterId
    				     }		
    			};
    	}
    	else{
    		var d={
    				"id":id,
    				"createTime":createTime,
    				"isSubmit":0,
    				"superior":superior,
    				"unitName" : unitName,
    				"contractCode" : contractCode,
    				"contractId" : contractId,
    				"proposer" : proposer,
    				"linkMan" : linkMan,
    				"linkManPhone" : linManPhone,
    				"afterSaleType" : afterSaleType,
    				"deviceName" : deviceName,
    				"deviceCode" : deviceCode,
    				"deviceNumber" : deviceNumber,
    				"questionDetail" : questionDetail,
    				"serviceTime" : serviceTime,
    				"submiter" : {
					     "id":submiterId
				     }			
    		}
    	}
    	jQuery.ajax({
    		type : 'post',
    		url : encodeURI(url),
    		data : JSON.stringify(d),
    		dataType : 'json',
    		contentType : 'application/json;charset=utf-8',
    		success : function(data) {
    			var taskId=data.ticketId;
    			var submiterId=jQuery("#submiter").val();
    			addTask("售后申请待提交","/ui/afterSaleTicket",submiterId,0,taskId)
    			delTask(taskId,"售后申请退回");
    			if(re==1){
    				url1 = window.rootPath+'/ui/afterSaleTicket'; 
    				window.location=url1;
	        	  }
	        	  else if(re==2){
	        		  var id=data.ticketId;
	        		  jQuery("#id").val(id);
	        		  var time=moment(data.createTime).format("YYYY-MM-DD HH:mm:ss")
	            	  jQuery("#ticketCreateTime").val(time);
	        		  fileUpload(id,fileType,null,numId);
	        	  }  
    		}
    	  });
}
    ////////////////合同选择弹窗////////
	//合同选择按钮
	  jQuery(".contractBtn").on('click',function(){
		  jQuery('#contractModal').modal('show');
	  });
	  //关联合同弹窗中合同信息table
	  var contractData={};
	  contractData.key='';
	  var contractTable;
	  jQuery(document).ready(function () {
		  contractTable = jQuery('#contractTable').DataTable({
	            "serverSide": true,
	            "ordering": false,
	            "iDisplayLength": 5,
	            "ajax": {
	                "dataType": "json",
	                "type": "get",
	                "cache": false,
	                "url":window.rootPath+ '/ui/afterSaleDeviceInfo/getContract',
	                "data": function (d) {
	                    return $.extend({}, d, contractData);
	                }
	            },
	            columns: [
	                {
	                	data: null
	                },
	                {
	                	data : null,
						defaultContent : "",
						render : function(data,type, full, meta) {
					var operate = '<button type="button" class="btn btn-info btn-sm linkBtn">关联</button>';
						return operate;
						}  
	                },
	                {
	                    data: 'supplierCode'
	                },
	                {
	                	data: 'contractType'
	                },
	                /*{
	                    data: null,
	                    render: function (data, type, full, meta) {
	                        var out = '<span class="badge badge-success">通过</span>';
	                        return out;
	                    }
	                },*/
	                {
	                    data: 'belongArea'
	                },
	                {
	                    data: 'totalSum'
	                },
	                {
	                    data: 'scheduleDate',
	                    render: function (data, type, full, meta) {
	                        if (data)
	                            return moment(data).format('YYYY/MM/DD');
	                        else
	                            return '';
	                    }
	                },
	                {
	                    data: 'deliveryDate',
	                    render: function (data, type, full, meta) {
	                        if (data)
	                            return moment(data).format('YYYY/MM/DD');
	                        else
	                            return '';
	                    }
	                },
	                {
	                    data: 'stop'
	                },
	                {
	                    data: 'freightCharge'
	                },
	                {
	                    data: 'projectName'
	                },
	                {
	                    data: 'orderUnit'
	                },
	                {
	                    data: 'orderAddress'
	                },
	                {
	                    data: 'orderDelegate'
	                },
	                {
	                    data: 'orderPhone'
	                },
	                {
	                    data: 'orderZip'
	                },
	                {
	                    data: 'orderArea'
	                },
	                {
	                    data: 'postUnit'
	                },
	                {
	                    data: 'postAddress'
	                },
	                {
	                    data: 'postDelegate'
	                },
	                {
	                    data: 'postPhone'
	                },
	                {
	                    data: 'postZip'
	                }
	                ],
	            "drawCallback": function (oSettings) {
	                var k = 0;
	                var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;

	                for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
	                    $('td:eq(0)', oSettings.aoData[oSettings.aiDisplay[k]].nTr).text(i + 1);
	                    k++;
	                }
	                contractTable.off('click', 'tr');
					contractTable.on('click','tr',function(event) {
					    event = event|| window.event;
						var target = event.target|| event.scrElement;
						var data = contractTable.row(this).data();
						if (target.className.indexOf('linkBtn') != -1) {
					    	linkContract(data);
						}
					return;
					});
	            }
	        });
		  //关联合同
		   var  linkContract=function(data){
			   $.springLemonDialog({
					content : '确认关联合同号为'+data.supplierCode+'的合同？',// 确认文本
					clickButton : function(sender, modal, index) {// 按钮事件处理
						if(index==0){
							jQuery("#contractId").val(data.id);
							jQuery("#contractCode").val(data.supplierCode);
							jQuery("#unitName").val(data.orderUnit)
							jQuery('#contractModal').modal('hide');
						}
						$(this).closeDialog(modal);
					}
				});
		   }
	  });
	  
	//查询
      jQuery('.searchBtn').on('click',function(){
          contractData.key=jQuery('#keyword').val();
          contractTable.draw();
      })
      //撤销查询
      jQuery('.resetBtn').on("click",function()
      {
          jQuery('#keyword').val('');
          contractData.key ='';
          contractTable.draw();
      });
	  
      /////////////////设备选择弹窗////////////////////
    //设备选择按钮
	  jQuery(".deviceBtn").on('click',function(){
		  var contractId = jQuery("#contractId").val();
		  if(contractId==''){
			  $.springLemonDialog({
					content : '请先关联合同',// 确认文本
					clickButton : function(sender, modal, index) {// 按钮事件处理
						$(this).closeDialog(modal);
					}
				});
		  }
		  else{
			  	deviceData.contractId=contractId;
			  	deviceTable.draw();
			  	jQuery('#deviceModal').modal('show');
		  }
	  });
	  //关联设备弹窗table
	//获取项目合同细目泵数据 服务器分页
	    var deviceData = {};
	    deviceData.contractId=jQuery('#contractId').val();
	    var deviceTable;
	    jQuery(document).ready(function () {
	    	deviceTable = jQuery('#deviceTable').DataTable({
	            "serverSide": true,
	            "ordering": false,
	            "iDisplayLength": 5,
	            "ajax": {
	                "dataType": "json",
	                "type": "get",
	                "cache": false,
	                "url":window.rootPath+ '/ui/contract/getDevice',
	                "data": function (d) {
	                    return $.extend({}, d, deviceData);
	                }
	            },
	            columns: [
	                {
	                	data: null
	                },
	                {
	    	            data: null,
	    	            defaultContent: "",
	    	            render: function (data, type, full, meta) {
	    	            	var operate = '<button type="button" class="btn btn-info btn-sm linkDeviceBtn">关联</button>';
							return operate;
	    	            }   
	                },
	                {
	                    data: 'productName'
	                },
	                {
	                    data: 'productType'
	                },
	                {
	                    data: 'subDivideType'
	                },
	                {
	                	data: 'productModel'
	                },
	                {
	                    data: 'isInventory'
	                },
	                {
	                    data: 'number'
	                },
	                {
	                    data: 'unitPrice'
	                },
	                {
	                    data: 'power'
	                },
	                {
	                    data: 'flowMaterial'
	                },
	                {
	                    data: 'transMedia'
	                },
	                {
	                    data: 'viscosity'
	                },
	                {
	                    data: 'flux'
	                },
	                {
	                    data: 'pumpLift'
	                },
	                {
	                    data: 'temperature'
	                },
	                {
	                    data: 'proportion'
	                },
	                {
	                    data: 'inPressure'
	                },
	                {
	                    data: 'effectiveNPSHA'
	                },
	                {
	                    data: 'mustMPSHA'
	                }
	                ],
	            "drawCallback": function (oSettings) {
	                var k = 0;
	                var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;

	                for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
	                    $('td:eq(0)', oSettings.aoData[oSettings.aiDisplay[k]].nTr).text(i + 1);
	                    k++;
	                }
	                deviceTable.off('click', 'tr');
					deviceTable.on('click','tr',function(event) {
					    event = event|| window.event;
						var target = event.target|| event.scrElement;
						var data = deviceTable.row(this).data();
						if (target.className.indexOf('linkDeviceBtn') != -1) {
					    	linkDevice(data);
						}
					return;
					});
	            }
	    	});
	           //关联设备
	            var linkDevice=function(data){
	 			   $.springLemonDialog({
	 					content : '确认关联设备名称为'+data.productName+'的设备？',// 确认文本
	 					clickButton : function(sender, modal, index) {// 按钮事件处理
	 						if(index==0){
	 							jQuery("#deviceId").val(data.id);
	 							jQuery("#deviceName").val(data.productName);
	 							jQuery("#deviceNumber").val(data.productModel);
	 							jQuery('#deviceModal').modal('hide');
	 						}
	 						$(this).closeDialog(modal);
	 					}
	 				});
	 		   }
	            
	        });
	    
///////////////////////附件上传下载///////////////////////////
		//传真，邮件
		jQuery(".upMail").on('click',function(){
			saveTicket(2,"传真邮件",'mailNum')
		});
		jQuery(".downMail").on('click',function(){
			var ticketId=jQuery("#id").val();
	    	filedown(ticketId,'传真邮件',1);
		});
		if(jQuery("#id").val()!=''){
			showANum(jQuery("#id").val(),'传真邮件',"mailNum");
		}
		//质量反馈表
		jQuery(".upQuality").on('click',function(){
			saveTicket(2,"质量反馈表",'qualityNum')
		});
		jQuery(".downQuality").on('click',function(){
			var ticketId=jQuery("#id").val();
	    	filedown(ticketId,'质量反馈表',1);
		});
		if(jQuery("#id").val()!=''){
			showANum(jQuery("#id").val(),'质量反馈表',"qualityNum");
		}
	    
		//技术方案
		jQuery(".upPlan").on('click',function(){
			saveTicket(2,"技术方案",'planNum');
		});
		jQuery(".downPlan").on('click',function(){
			var ticketId=jQuery("#id").val();
	    	filedown(ticketId,'技术方案',1);
		});
		if(jQuery("#id").val()!=''){
			showANum(jQuery("#id").val(),'技术方案',"planNum");
		}
		
		//返厂泵处理表
		jQuery(".upDealForm").on('click',function(){
			saveTicket(2,"返厂泵处理表",'dealFormNum');
		});
		jQuery(".downDealForm").on('click',function(){
			var ticketId=jQuery("#id").val();
	    	filedown(ticketId,'返厂泵处理表',1);
		});
		if(jQuery("#id").val()!=''){
			showANum(jQuery("#id").val(),'返厂泵处理表',"dealFormNum");
		}
		
		//其它
		jQuery(".upOther").on('click',function(){
			saveTicket(2,"其它",'otherNum');
		});
		jQuery(".downOther").on('click',function(){
			var ticketId=jQuery("#id").val();
	    	filedown(ticketId,'其它',1);
		});
		if(jQuery("#id").val()!=''){
			showANum(jQuery("#id").val(),'其它',"otherNum");
		}
		
		//三包办理明细
		jQuery(".upDetail").on('click',function(){
			saveTicket(2,"三包办理明细",'detailNum');
		});
		jQuery(".downDetail").on('click',function(){
			var ticketId=jQuery("#id").val();
	    	filedown(ticketId,'三包办理明细',1);
		});
		if(jQuery("#id").val()!=''){
			showANum(jQuery("#id").val(),'三包办理明细',"detailNum");
		}
		
		//执行过程
		jQuery(".upProcess").on('click',function(){
			saveTicket(2,"执行过程",'processNum');
		});
		jQuery(".downProcess").on('click',function(){
			var ticketId=jQuery("#id").val();
	    	filedown(ticketId,'执行过程',1);
		});
		if(jQuery("#id").val()!=''){
			showANum(jQuery("#id").val(),'执行过程',"processNum");
		}
		
		//三包图片
		jQuery(".upPicture").on('click',function(){
			saveTicket(2,"执行过程",'processNum');
		});
		jQuery(".downPicture").on('click',function(){
			var ticketId=jQuery("#ticketId").val();
	    	filedown(ticketId,'三包图片',1);
		});
		if(jQuery("#id").val()!=''){
			showANum(jQuery("#id").val(),'三包图片',"pictureNum");
		}
		
		//返厂维修意见
		jQuery(".backAdviceUp").on('click',function(){
			saveTicket(2,"返厂维修意见",'backAdviceNum');
		});
		jQuery(".backAdviceDown").on('click',function(){
			var ticketId=jQuery("#id").val();
	    	filedown(ticketId,'返厂维修意见',1);
		});
		if(jQuery("#id").val()!=''){
			showANum(jQuery("#id").val(),'返厂维修意见',"backAdviceNum");
		}
		////提交人
		jQuery("#submiter").select2().trigger("change");